<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :xs="24" :sm="9" :md="7" :lg="5">
                <div class="grid-content bg-purple">
                    <el-input v-model="searchMsg" placeholder="请输入角色名称"></el-input>
                </div>
            </el-col>
            <el-col :xs="12" :sm="10" :md="10" :lg="10">
                <div class="grid-content bg-purple-light">
                    <el-button type="primary" icon="search" @click="filterData">搜索</el-button>
                </div>
            </el-col>
            <el-col :xs="12" :sm="5" :md="7" :lg="9">
                <div class="grid-content bg-purple-light" style="float:right">
                    <el-button icon="edit" @click="createRole()">新建角色</el-button>
                </div>
            </el-col>
        </el-row>
        <el-table :data="infos.pageData" v-loading.body="listLoading" element-loading-text="加载中..." border style="width: 100%;margin:20px 0">
            <el-table-column label="序号" min-width="80px">
                <template scope="scope">
                    <span>{{ scope.$index+1+(pageConfig.curPage-1)*pageConfig.size }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属组织" min-width="140px">
                <template scope="scope">
                    <span>{{ scope.row.companyName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="角色名称" min-width="100px">
                <template scope="scope">
                    <span>{{scope.row.roleName}}</span>
                </template>
            </el-table-column>
            <el-table-column label="权限数量" min-width="120px">
                <template scope="scope">
                    <div @click="roleDetailShow(scope.row.roleId)" class="cellStyle">
                        <span>{{ scope.row.menuCount }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="账号数量" min-width="140px">
                <template scope="scope">
                    <div @click="goWhere('Account',scope.row.roleId,scope.row.accountCount)" class="cellStyle">
                        <span>{{ scope.row.accountCount }}</span>
                    </div> 
                </template>
            </el-table-column>
            <el-table-column label="账号组数量" min-width="100px">
                <template scope="scope">
                    <div @click="goWhere('AccountGroup',scope.row.roleId,scope.row.departCount)" class="cellStyle">
                        <span>{{ scope.row.departCount }}</span>
                    </div> 
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="220px">
                <template scope="scope">
                    <el-button size="small" type="success" @click="editRole(scope.row.roleId)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteConfirm(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination style="padding:0;" @current-change="handleCurrentChange" :current-page.sync="pageConfig.curPage" :page-size="pageConfig.size" layout="total, prev, pager, next, jumper" :total="pageConfig.total">
            </el-pagination>
        </div>
    
        <!-- dialog编辑框 -->
        <el-dialog title="角色信息" size="small" :visible.sync="roleEditVisible">
            <el-form :model="roleInfo" style="margin-bottom:-30px" :rules="rules" ref="roleInfo">
                <el-form-item label="所属企业" :label-width="formLabelWidth" prop="companyId">
                    <el-select v-model="roleInfo.companyId" placeholder="请选择所属企业" :style="inputWidth" :disabled="roleInfo.disabled">
                        <el-option v-for="list in companyList" :key="list.companyId" :label="list.companyName" :value="list.companyId.toString()"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="roleInfo.roleName" auto-complete="off" :style="inputWidth" placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item label="权限配置" :label-width="formLabelWidth" prop="icon">
                    <el-button size="small" @click="checkedAll(true)">全选</el-button>
                    <el-button size="small" @click="checkedAll(false)">全不选</el-button>
                </el-form-item>
    
                <el-form-item label="" :label-width="formLabelWidth">
                    <el-table :data="gridData" v-if="gridData.length>0">
                        <el-table-column label="一级菜单">
                            <template scope="scope">
                                <el-checkbox-group v-model="checkList" @change="handleCheckedGroupChange(scope.row)">
                                    <el-checkbox :label="scope.row.topMenu" :checked="scope.row.topMenu.selectState" :key="scope.row.topMenu.menuId">{{scope.row.topMenu.menuName}}</el-checkbox>
                                </el-checkbox-group>
                            </template>
                        </el-table-column>
                        <el-table-column label="二级菜单" min-width="300">
                            <template scope="scope">
                                <el-checkbox-group v-model="checkList">
                                    <el-checkbox v-for="rows in scope.row.secMenu" @change="handleCheckedItemsChange(scope.row,rows)" :checked="rows.selectState" :label="rows" :key="rows.menuId">{{rows.menuName}}</el-checkbox>
                                </el-checkbox-group>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roleEditVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('roleInfo',roleInfo.type )">确 定</el-button>
            </div>
        </el-dialog>
    
        <el-dialog :title="roleDetail.title" :visible.sync="roleDetail.menuDetailVisible" size="tiny">
            <el-table :data="roleDetail.roleData">
                <el-table-column label="一级菜单" width="110">
                    <template scope="scope">
                        <span :class="{'checkedMenu':scope.row.topMenu.selectState===true,'unCheckedMenu':scope.row.topMenu.selectState===false}">{{scope.row.topMenu.menuName}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="二级菜单">
                    <template scope="scope">
                        <span v-for="rows in scope.row.secMenu" :key='rows.menuId' :class="{'checkedMenu':rows.selectState===true,'unCheckedMenu':rows.selectState===false}">{{rows.menuName}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roleDetail.menuDetailVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style>
.cellStyle {
    width: 100%;
    display: inline-block;
    cursor: pointer;
    color: #20A0FF;
}

.cellStyle:hover {
    font-size: 1.2em;
    font-weight: bold;
    color: deeppink
}

.checkedMenu {
    font-weight: bold;
    color: #20A0FF;
    margin-right: 10px;
}

.unCheckedMenu {
    color: #ddd;
    margin-right: 10px;
}
</style>
    
<script>
export default {
    data() {
        return {
            listLoading: true,
            searchMsg: '',
            companyList: [],
            infos: {
                tableData: [],
                re_tableData: [],
                pageData: []
            },
            roleInfo: {
                companyId: '',
                roleName: '',
                type: 'new'
            },
            roleEditVisible: false,
            checkList: [],
            gridData: [],
            roleDetail: {
                menuDetailVisible: false,
                title: '',
                roleData: []
            },
            pageConfig: {
                curPage: 1,
                total: null,
                size: 9,
            },
            inputWidth: {
                width: '60%'
            },
            formLabelWidth: '100px',
            rules: {
                companyId: [
                    { required: true, message: '请选择所属企业', trigger: 'change' },
                ],
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在不超过 20 个字符', trigger: 'blur' }
                ]
            },
        }
    },
    created() {
        this.getRoleList();
    },
    methods: {
        getRoleList() {
            this.listLoading = true;
            let _url =  '/sys/role/allRoles';
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.infos.tableData = this.infos.re_tableData = response.data;
                        this.pageConfig.total = this.infos.re_tableData.length;
                        this.listLoading = false;
                        this.pageChange(this.pageConfig.curPage);
                    } else {
                        this.listLoading = false;
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    setTimeout(() => {
                        this.listLoading = false;
                    }, 400);
                    console.log(response)
                })
        },
        getCompanyList() {
            this.companyList = [];
            let _url =  '/sys/company/list';
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.companyList = response.data;
                    } else {
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    console.log(response)
                })
        },
        filterData() {
            this.infos.re_tableData = this.infos.tableData.filter((item) => {
                return item.roleName.indexOf(this.searchMsg) > -1;
            });
            this.pageConfig.total = this.infos.re_tableData.length;
            this.pageChange(this.pageConfig.curPage);
        },
        createRole() {
            this.resetForm();
            this.checkList = [];
            this.gridData = [];
            this.getCompanyList();
            //获取所有菜单
            let _url =  '/sys/menu/selectMenu';
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.gridData = response.data;
                        this.roleEditVisible = true;
                    } else {
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    console.log(response)
                })
        },
        editRole(roleId) {
            this.resetForm();
            this.checkList = [];
            this.gridData = [];
            this.getCompanyList();
            //获取所有菜单，包括选中信息
            let _url =  '/sys/role/detail/' + roleId;
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.gridData = response.data.menus;
                        this.roleInfo = response.data;
                        this.roleInfo.type = 'edit';
                        this.roleEditVisible = true;
                    } else {
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    console.log(response)
                })
        },
        handleCurrentChange(val) {
            this.pageConfig.curPage = val;
            this.pageChange(val);
        },
        pageChange(page) {
            this.infos.pageData = this.infos.re_tableData.slice((page - 1) * this.pageConfig.size, page * this.pageConfig.size);
        },
        goWhere(path,id,count) {
            if(count>0){
                this.$router.push({path:path,query: {id: id}});
            }else{
                this.showWarning('该角色下无账号(组)信息 !', '警告');
            }
        },
        roleDetailShow(roleId) {
            this.roleDetail.roleData = [];
            this.roleDetail.title = '';
            let _url =  '/sys/role/detail/' + roleId;
            this.$http.get(_url)
                .then((response) => {
                    if (response.code === 0) {
                        this.roleDetail.roleData = response.data.menus;
                        this.roleDetail.title = response.data.companyName + ' ' + response.data.roleName + ' 角色权限';
                        this.roleDetail.menuDetailVisible = true;
                    } else {
                        console.log(response.statusText)
                    }
                }).catch((response) => {
                    console.log(response)
                })
        },
        deleteConfirm(info) {
            const h = this.$createElement;
            this.$msgbox({
                title: '删除角色',
                message: h('p', null, [
                    h('span', null, '是否删除 '),
                    h('span', { style: 'color: #20A0FF;font-size:1.2em;font-weight:bold' }, info.roleName),
                    h('span', null, ' 这个角色？'),
                ]),
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '删除中...';
                        setTimeout(() => {
                            done();
                            setTimeout(() => {
                                instance.confirmButtonLoading = false;
                            }, 100);
                        }, 400);
                    } else {
                        done();
                    }
                }
            }).then((action) => {
                if (action === 'confirm') {
                    this.roleDelete(info);
                } else {
                    showMessage('已取消删除', 'info');
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        roleDelete(info) {
            let _url =  '/sys/role/' + info.companyId + '/' + info.roleId;
            this.$http.delete(_url).then((response) => {
                if (response.code === 0) {
                    this.getRoleList();
                    this.showMessage('删除成功!', 'success');
                } else {
                    if (response.code === -1) {
                        console.log(response.statusText);
                    } else {
                        this.showWarning(response.msg, '无法操作角色');
                    }
                }
            }).catch((response) => {
                console.log(response)
            })
        },
        submitForm(formName, type) {
            let _url =  '/sys/role';
            let tepArr = [];
            this.gridData.forEach(item => {
                if (item.topMenu.selectState === true) { tepArr.push(item.topMenu) }
                item.secMenu.forEach(list => {
                    if (list.selectState === true) { tepArr.push(list) }
                });
            });
            this.roleInfo.menus = tepArr;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (type === 'new') {
                        this.$http.post(_url, this.roleInfo)
                            .then((response) => {
                                if (response.code === 0) {
                                    this.roleEditVisible = false;
                                    this.getRoleList();
                                    this.showMessage('创建成功!', 'success');
                                } else {
                                    if (response.code === -1) {
                                        console.log(response.statusText);
                                    } else {
                                        this.showWarning(response.msg, '创建角色失败');
                                    }
                                }
                            }).catch((response) => {
                                console.log(response)
                            })
                    } else {
                        this.$http.put(_url, this.roleInfo)
                            .then((response) => {
                                if (response.code === 0) {
                                    this.roleEditVisible = false;
                                    this.getRoleList();
                                    this.showMessage('修改成功!', 'success');
                                } else {
                                    if (response.code === -1) {
                                        console.log(response.statusText);
                                    } else {
                                        this.showWarning(response.msg, '无法操作角色');
                                    }
                                }
                            }).catch((response) => {
                                console.log(response)
                            })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        showWarning(msg, title) {
            this.$alert(msg, title, {
                showConfirmButton: false,
                showCancelButton: true,
                cancelButtonText: '关闭',
                type: 'warning'
            });
        },
        showMessage(msg, type) {
            this.$message({
                message: msg,
                type: type
            });
        },
        handleCheckedGroupChange(rows) {
            if (event.target.checked) {
                rows.topMenu.selectState = true;
                rows.secMenu.forEach((item) => {
                    if (!item.selectState) {
                        this.checkList.push(item);
                        item.selectState = true;
                    }
                });
            } else {
                rows.topMenu.selectState = false;
                rows.secMenu.forEach((item) => {
                    if (item.selectState) {
                        this.checkList.forEach((elem, index) => {
                            if (elem.menuId === item.menuId) {
                                this.checkList.splice(index, 1);
                                item.selectState = false;
                            }
                        });
                    }
                });
            }
        },
        handleCheckedItemsChange(rows, item) {
            let noChecked = true;
            if (event.target.checked) {
                item.selectState = true;
                if (!rows.topMenu.selectState) {
                    this.checkList.push(rows.topMenu);
                    rows.topMenu.selectState = true;
                }
            } else {
                item.selectState = false;
                rows.secMenu.forEach((elem) => {
                    if (elem.selectState === true) {
                        noChecked = false;
                        return
                    }
                });
                if (noChecked) {
                    this.checkList.forEach((elem, index) => {
                        if (elem.menuId === rows.topMenu.menuId) {
                            this.checkList.splice(index, 1);
                            rows.topMenu.selectState = false;
                        }
                    });
                }
            }
        },
        checkedAll(boolean) {
            this.checkList = [];
            this.gridData.forEach((items) => {
                if (boolean) {
                    items.topMenu.selectState = true;
                    this.checkList.push(items.topMenu);
                    items.secMenu.forEach((elem) => {
                        elem.selectState = true;
                        this.checkList.push(elem);
                    });
                } else {
                    items.topMenu.selectState = false;
                    items.secMenu.forEach((elem) => {
                        elem.selectState = false;
                    });
                }
            })
        },
        resetForm() {
            this.roleInfo = {
                companyId: '',
                roleName: '',
                type: 'new'
            };
            if (this.$refs['roleInfo']) {
                this.$refs['roleInfo'].resetFields();
            }
        },
    }
}
</script>